"""
文章相关的Pydantic schema
"""
from pydantic import BaseModel, Field, validator
from typing import List, Optional
from datetime import datetime
from enum import Enum


class ArticleStatus(str, Enum):
    """文章状态枚举"""
    DRAFT = "draft"
    PUBLISHED = "published"
    FAILED = "failed"


class MediaAssetResponse(BaseModel):
    """媒体素材响应模型"""
    id: str
    media_id: str
    original_url: Optional[str]
    media_type: str
    position: Optional[int]
    uploaded_at: datetime

    class Config:
        from_attributes = True


class ArticleBase(BaseModel):
    """文章基础模型"""
    title: str = Field(..., max_length=200, description="文章标题")
    summary: Optional[str] = Field(None, max_length=500, description="文章摘要")
    content: str = Field(..., min_length=100, description="文章内容")

    @validator('title')
    def validate_title(cls, v):
        if not v or not v.strip():
            raise ValueError('标题不能为空')
        if len(v) > 60:
            raise ValueError('标题不能超过60个字符')
        return v.strip()

    @validator('summary')
    def validate_summary(cls, v):
        if v and len(v) > 100:
            raise ValueError('摘要不能超过100个字符')
        return v.strip() if v else v

    @validator('content')
    def validate_content(cls, v):
        if not v or not v.strip():
            raise ValueError('内容不能为空')
        if len(v) < 100:
            raise ValueError('内容长度不能少于100字符')
        return v.strip()


class ArticleCreate(BaseModel):
    """创建文章请求模型"""
    theme_id: str = Field(..., description="主题ID")
    
    
class ArticleGenerateRequest(BaseModel):
    """生成文章请求模型"""
    theme_id: str = Field(..., description="主题ID")
    include_images: bool = Field(True, description="是否生成图片")
    num_content_images: int = Field(3, ge=0, le=10, description="内容配图数量")


class ArticleResponse(ArticleBase):
    """文章响应模型"""
    id: str
    theme_id: str
    status: ArticleStatus
    cover_image_id: Optional[str]
    draft_id: Optional[str]
    generated_at: datetime
    published_at: Optional[datetime]
    media_assets: List[MediaAssetResponse] = []

    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda v: v.isoformat()
        }


class ArticleWithTheme(ArticleResponse):
    """包含主题信息的文章响应模型"""
    theme: Optional[dict] = None


class ArticleListResponse(BaseModel):
    """文章列表响应模型"""
    items: List[ArticleResponse]
    total: int
    page: int
    page_size: int
    has_next: bool


class ArticleGenerationResult(BaseModel):
    """文章生成结果模型"""
    article: Optional[ArticleResponse]
    success: bool
    message: str
    generation_time: float